'use client';

import { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { io, Socket } from 'socket.io-client';
import { useSession } from 'next-auth/react';

// Socket上下文类型
interface SocketContextType {
  socket: Socket | null;
  isConnected: boolean;
  reconnect: () => void;
  users: Array<{
    socketId: string;
    name: string;
    color: string;
  }>;
}

// 创建上下文
const SocketContext = createContext<SocketContextType | undefined>(undefined);

// Socket提供者组件
export function SocketIOProvider({ 
  children,
  projectId
}: { 
  children: ReactNode;
  projectId?: string;
}) {
  const [socket, setSocket] = useState<Socket | null>(null);
  const [isConnected, setIsConnected] = useState(false);
  const [users, setUsers] = useState<Array<any>>([]);
  const { data: session } = useSession();

  // 连接Socket
  const connectSocket = () => {
    try {
      console.log('[SocketProvider] 连接Socket...');
      
      // 关闭现有连接
      if (socket) {
        socket.disconnect();
      }
      
      // 创建Socket实例
      const socketInstance = io({
        reconnectionAttempts: 5,
        reconnectionDelay: 1000,
        transports: ['websocket', 'polling'] // 优先使用WebSocket
      });
      
      setSocket(socketInstance);
      
      // 监听连接状态
      socketInstance.on('connect', () => {
        console.log('[SocketProvider] Socket连接成功', socketInstance.id);
        setIsConnected(true);
        
        // 如果有项目ID，加入项目房间
        if (projectId) {
          console.log(`[SocketProvider] 加入项目房间: ${projectId}`);
          socketInstance.emit('join-project', { 
            projectId, 
            userName: session?.user?.name || '匿名用户'
          });
        }
      });

      socketInstance.on('disconnect', () => {
        console.log('[SocketProvider] Socket已断开');
        setIsConnected(false);
      });

      socketInstance.on('connect_error', (error) => {
        console.error('[SocketProvider] 连接错误:', error);
        setIsConnected(false);
      });
      
      // 监听用户列表更新
      socketInstance.on('users-update', (roomUsers) => {
        console.log('[SocketProvider] 房间用户更新:', roomUsers);
        setUsers(roomUsers);
      });
      
    } catch (error) {
      console.error('[SocketProvider] Socket连接失败:', error);
      setIsConnected(false);
    }
  };

  // 重新连接
  const reconnect = () => {
    if (socket) {
      socket.disconnect();
    }
    connectSocket();
  };

  // 初始化连接
  useEffect(() => {
    if (projectId) {
    connectSocket();
    }

    return () => {
      // 清理连接
      if (socket) {
        console.log('[SocketProvider] 清理Socket连接');
        socket.disconnect();
      }
    };
  }, [projectId, session?.user?.name]); // 当项目ID或用户名变化时重新连接

  // 提供上下文值
  const contextValue: SocketContextType = {
    socket,
    isConnected,
    reconnect,
    users
  };

  return (
    <SocketContext.Provider value={contextValue}>
      {children}
    </SocketContext.Provider>
  );
}

// 自定义Hook使用Socket上下文
export function useSocket() {
  const context = useContext(SocketContext);
  
  if (context === undefined) {
    throw new Error('useSocket必须在SocketProvider内部使用');
  }
  
  return context;
}

export default SocketIOProvider;
